package com.app.configuration.web.mvc.interceptors;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.NamedThreadLocal;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import com.app.util.common.IPUtil;
import com.app.util.common.ObjUtil;
import com.app.util.common.RequestUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.common.UuidUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.common.GlobaUser;
import com.suncnpap.system.model.Admin;
import com.suncnpap.system.model.Menu;
import com.suncnpap.system.service.MenuService;
/**
    *请求拦截，以及权限认证
 * @author chenl
 *
 */
@Component
public class UserRightsInterceptor implements HandlerInterceptor{

	private static final Logger log = Logger.getLogger(UserRightsInterceptor.class);
	private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
	
	private NamedThreadLocal<Long>  beginTime = new NamedThreadLocal<Long>("beginTime");
	
	
	//忽略的路径
	@Value("${userRightInterceptor.excludeUrl}")
	String userRightExcludeUrl;						//不进行拦截的url
	
	@Value("${userRightInterceptor.excludePath}")
	String userRightExcludePath;			//不进行权限拦截的路径
	
	@Value("${sysConfig.recordVisitUrl}")
	boolean recordVisitUrl;					//是否记录访问url信息
	
	@Autowired
	ThreadPoolTaskExecutor threadPoolTaskExecutor;
	
	@Autowired
	MenuService menuService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		
		
//		User user = Globa.getUser();
		
		
//		String contextPath = request.getContextPath();
//		String uri = request.getRequestURI();
//		if(uri.indexOf(contextPath) == 0){
//			uri = uri.substring(contextPath.length());
//		}
//		if(uri.endsWith("/")) uri = uri.substring(0,uri.length()-1);
//		
//		if(uri.equals("")) {
//			return true;
//			
//		}else {		//对其进行权限认证
//			
//			
//			
//			//验证是否在忽略的路径中
//			boolean isValid = false;
//			
//			
//			if(!userRightExcludeUrl.equals("")) {
//				String[] excludeUrlArr = userRightExcludeUrl.split(",");
//				for(int i=0;i<excludeUrlArr.length;i++) {
//					String tempUrl = excludeUrlArr[i];
//					if(uri.equals(tempUrl)) {
//						isValid = true;
//						break;
//					}
//				}
//			}
//			
//			//访问路径的验证
//			if(isValid == false && userRightExcludePath != null && !userRightExcludePath.equals("")) {
//				String[] excludePathArr = userRightExcludePath.split(",");
//				for(int i=0;i<excludePathArr.length;i++) {
//					String tempPath = excludePathArr[i];		//配置的路劲如/upload/**
//					tempPath = tempPath.replace("**", "");
//					
//					//当前的访问路径如 /upload/aaa/
//					if(uri.startsWith(tempPath)) {
//						isValid = true;
//					}
//				}
//			}
//			
//			
//			if(isValid) {	//表示不需要进行验证，直接通过
////				info.setStrFailInfo("地址在白名单中");
//				return true;
//			}
//			
//			
//			
////			if(user != null) {
////				
////				List<Menu> list = user.getMenuList();		//当前登录人所拥有的权限 	
////				
////				//获取当前的路劲对应的菜单信息
////				Menu visitMenu = menuService.findByUrl(uri);
////				if(visitMenu == null) {	//为空，或者不需要验证
//////					info.setStrFailInfo("地址不在菜单控制内");
////					return true;
////				}else if("0".equals(visitMenu.getStrIsAuthentic())){
//////					info.setStrFailInfo("地址不认证");
////					return true;
////				}else {
////				
//////					info.setStrMenuName(visitMenu.getStrName());
//////					info.setStrLinkId(visitMenu.getStrId());
////					boolean hasRight = false;
////					for(Menu menu : list) {
////						if(uri.equals(menu.getStrUrl())) {
////							hasRight = true;
////							break;
////						}
////					}
////					if(hasRight) {
//////						info.setStrFailInfo("权限认证通过");
////						return true;
////					}else {					//未有权限访问
//////						info.setStrState("1");
//////						info.setStrFailInfo("没有权限访问");
//////						info.setStrEndDate(format.format(new Date()));
//////	            		info.setIntUseTime((int)(new Date().getTime() - begin));	//使用时间
////	            		
////		                if(RequestUtil.isAjax(request)){
////		                	Map<String,Object> map = new HashMap<String,Object>();
////		                	map.put("globa_nopermission", "-1");
////		                	map.put("tip","<font color='red'><b>您无权限访问</b></font>");
////		                	ResponseUtil.writeJson(map, response);
////		                }else{ 
////		                	ResponseUtil.write("<script language='javascript' charset=UTF-8>alert('您无权限访问');</script>",response);
////		                }
////		                
//////		                log.debug("拒绝请求,共耗时："+info.getIntUseTime()+";=====请求uri："+info.getStrUri());
////		                
////		                if(recordVisitUrl) {	//需要记录时，保存入库
////			                threadPoolTaskExecutor.execute(new Runnable() {
////			        			@Override
////			        			public void run() {
////			        				// TODO Auto-generated method stub
//////			        				info.setStrId(UuidUtil.get32UUID());
//////			        		 		logVisitService.add(info);
////			        			}
////			        		});
////		                }
////						
////						return false;
////					}
////				}
////			}
//			
//		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		if(response.getStatus()==500){  
//			LogVisit info = visitThreadLocal.get();
//			info.setStrState("1");
//			info.setStrFailInfo("500错误");
        }else if(response.getStatus()==404){  

//        	LogVisit info = visitThreadLocal.get();
//        	info.setStrState("1");
//			info.setStrFailInfo("404错误");
        }else if(response.getStatus()==400){  

//        	LogVisit info = visitThreadLocal.get();
//        	info.setStrState("1");
//			info.setStrFailInfo("400错误");
        }else if(response.getStatus() != 200) {
//        	LogVisit info = visitThreadLocal.get();
//        	info.setStrState("1");
//			info.setStrFailInfo(response.getStatus()+"错误");
        }
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
//		LogVisit info = visitThreadLocal.get();
//		info.setStrEndDate(format.format(new Date()));
//		info.setIntUseTime((int)(new Date().getTime() - beginTime.get()));	//使用时间
		
//		log.debug("完成请求,共耗时："+info.getIntUseTime()+";=====请求uri："+info.getStrUri());
		
		
		if(recordVisitUrl) {	//需要记录访问记录，则记录
			threadPoolTaskExecutor.execute(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					//保存入库
//					info.setStrId(UuidUtil.get32UUID());
//					logVisitService.add(info);
				}
			});
		}
		

	}
	
	
	






}
